package core;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import model.UserGroup;

public class CurrentUser extends model.User{
	private static PgSQL db = PgSQL.getInstance();
	protected UserGroup group = null;
	HttpSession session = null;
	
	public CurrentUser(HttpServletRequest request){
		this(request.getSession());
	}
	
	public CurrentUser(HttpSession session){	
		this.session = session;
		
		Object uid_obj = session.getAttribute("uid");
		if(uid_obj != null){
			this.uid = Tool.intval(uid_obj.toString());

			if(this.uid > 0){
				this.username = session.getAttribute("username").toString();
				setGroup((UserGroup) session.getAttribute("usergroup"));
				
				if(this.username == null || this.group == null){
					session.invalidate();
					this.uid = 0;
					resetUserGroup();
				}

			}else{
				resetUserGroup();
			}
		}
	}
	
	public boolean login(String email, String password){
		if(email == null || password == null){
			return false;
		}
		
		password = Tool.md5(password);
		
		String sql = "SELECT u.uid,u.username,g.* FROM qz_user u LEFT JOIN qz_usergroup g ON g.groupid=u.groupid WHERE u.email=? AND u.password=?";
		ResultSet rs = db.query(sql, email, password);
		
		try{
			if (rs.next()) {
				setUid(rs.getInt(1));
				setUsername(rs.getString(2));
				session.setAttribute("uid", this.uid);
				session.setAttribute("username", this.username);
	
				UserGroup g = new UserGroup();
				g.setGroupId(rs.getInt(3));
				g.setGroupName(rs.getString(4));
				g.setPermission(rs.getInt(5));
				session.setAttribute("usergroup", g);
				setGroup(g);
	
				return true;
			}else{
				return false;
			}
		}catch(SQLException e){
			e.printStackTrace();
		}
		
		return false;
	}
	
	public boolean isLoggedIn(){
		return this.uid > 0;
	}
	
	public boolean register(String username, String email, String password){
		String pwmd5 = Tool.md5(password);
		
		int affected_rows = db.update("INSERT INTO qz_user VALUES (nextval('uid'),?,?,?)", username, email, pwmd5);
	
		if (affected_rows == 1) {
			this.login(email, password);
			return true;
		}
		
		return false;
	}
	
	public boolean changePassword(String old_pwd, String new_pwd){
		old_pwd = Tool.md5(old_pwd);
		String Query = "SELECT password FROM qz_user WHERE uid=?";
		try{
			PreparedStatement ps = db.prepareStatement(Query);
			ps.setInt(1, uid);
			ResultSet rs = ps.executeQuery();
			if (rs.next()) {
				String password = rs.getString(1);
				if (!old_pwd.equals(password)) {
					return false;
				}
				PreparedStatement st = db.prepareStatement("UPDATE qz_user SET username=?,password=? WHERE uid=?");
				st.setString(1, username);
				st.setString(2, Tool.md5(new_pwd));
				st.setInt(3, uid);
				st.executeUpdate();
				
				return true;
			}
		}catch(SQLException e){
			e.printStackTrace();
		}
		
		return false;
	}
	
	public void setGroupId(int id){
		this.groupid = id;
		this.group = UserGroup.fromId(id);
	}
	
	public void setGroup(UserGroup group){
		this.group = group;
		if(group != null){
			setGroupId(group.getGroupId());
		}
	}
	
	public UserGroup getGroup(){
		if(group == null){
			resetUserGroup();
		}
		
		return group;
	}
	
	public String getGroupName(){
		return this.getGroup().getGroupName();
	}
	
	protected void resetUserGroup(){
		PgSQL db = PgSQL.getInstance();
		ResultSet rs = db.query("SELECT * FROM qz_usergroup WHERE groupid=0");
		try{
			if(rs.next()){
				setGroup(UserGroup.fromDatabase(rs));
			}
		}catch(SQLException e){
			e.printStackTrace();
		}
	}
}
